<?php

namespace app\service;

use app\common\BaseService;
use app\model\Show as ShowModel;

class ShowService extends BaseService
{
  public static function getInstance(): ShowService
  {
    return parent::getInstance();
  }

  public static function getModel(): ShowModel
  {
    return ShowModel::getInstance();
  }

  /*
   * 列表
   */
  public static function getShowList($condition, $page, $pageSize = 30, $order= ['id' => 'desc']) {
    return self::getModel()->getDataDetail($condition, $page, $pageSize, $order);
  }
  /*
   * 分页
   */
  public static function getShowPager($condition, $page, $pageSize = 30) {
    return self::getModel()->pager($condition, $page, $pageSize);
  }

  /*
   * 获取所有数据
   */
  public static function getAllShow($conditions, $order) {
    $result = self::getModel();
    foreach ($conditions as $item) {
      list($field, $value, $op) = $item;
      if (!$op) {
        $op = '=';
      }
      $result = $result->where($field, $op, $value);
    }
    if ($order) {
      $result = $result->order($order);
    }
    return $result->select()->toArray();
  }

  public static function createShow($data) {
    $oid = '';
    if (isset($data['oid']) && $data['oid']) {
      $oid = $data['oid'];
    } else {
      // 获取订单号
      $oid = self::getModel()->field(['max(oid)+1 as oid'])->select()->toArray();
      if (isset($oid[0])) {
        $oid = $oid[0]['oid'];
      } else {
        $oid = 0;
      }
    }
    // 获取仓库数据
    $house = HouseService::getModel()
      ->find($data['model'])
      ->toArray();
    // 新增show_t
    $insertShow = [
      'oid' => $oid,
      'date' => $data['date'] ? $data['date'] : null,
      'product' => $house['product'] ? $house['product'] : '',
      'model' => $house['model'] ? $house['model'] : '',
      'productn' => $house['productn'] ? $house['productn'] : '',
      'customer' => $data['customer'] ? trim($data['customer']) : '',
      'address' => $data['address'] ? $data['address'] : '',
      'cname' => $data['cname'] ? $data['cname'] : '',
      'phone' => $data['phone'] ? str_replace(' ', '',$data['phone']) : '',
      'state' => $data['state'] ? $data['state'] : 0,
      'cost' => $house['nowcost'] ? $house['nowcost'] : 0,
      'amoumt' => $data['amoumt'] ? $data['amoumt'] : 0,
      'other' => $data['other'] ? $data['other'] : '',
      'installtime' => $data['installtime'] ? $data['installtime'] : null,
      'itime' => $data['itime'] ? $data['itime'] : null,
      'states' => $data['states'] ? $data['states'] : 1,
      'backtime' => null,
      'new' => $data['new'],
      'unit' => $house['unit'] ? $house['unit'] : '',
      'price' => 0,
      'discount' => 0,
      'tprice' => 0,
      'paid' => 0
    ];
    // 更新house
    $updateHouse = [];
    if ($data['new']) {
      $updateHouse['amoumt'] = $house['amoumt'] - $data['amoumt'];
    } else {
      $updateHouse['oldamoumt'] = $house['oldamoumt'] - $data['amoumt'];
    }
    // 是否待定
    if ($data['states'] == 3) {
      if ($data['new']) {
        $updateHouse['wamoumt'] = $house['wamoumt'] + $data['amoumt'];
      } else {
        $updateHouse['oldwamoumt'] = $house['oldwamoumt'] + $data['amoumt'];
      }
    }
    $houseId = $house['id'];
    self::getModel()->startTrans();
    try {
      if ($insertShow) {
        $res = self::getModel()->save($insertShow);
        if (!$res) {
          throw new \Exception('新增order失败');
        }
      }
      if ($updateHouse) {
        $res1 = HouseService::getModel()
          ->where('id', '=', $houseId)
          ->update($updateHouse);
        if (!$res1) {
          throw new \Exception('修改house失败');
        }
      }
      self::getModel()->commit();
      return ['status' => true, 'msg' => 'ok'];
    } catch (\Exception $e) {
      self::getModel()->rollback();
      return ['status' => false, 'msg' => $e->getMessage()];
    }
  }

  /*
   * 删除
   */
  public static function deleteShow($id) {
    // 获取订单数据
    $show = self::getModel()->find($id)->toArray();
    // 获取仓库数据
    $house = HouseService::getModel()
      ->where('model', '=', $show['model'])
      ->select()
      ->toArray();
    $house = isset($house[0]) ? $house[0] : [];
    //现成本 = 总价 / 数量
    // 总价 = (当前可售+当前旧品可售+待出库库存+待出库旧品库存) * 当前成本 + (订单数量 * 订单成本)
    // 数量 = 当前可售 + 当前旧品可售 + 订单数量
    $total = ($house['amoumt'] + $house['oldamoumt'] + $house['wamoumt'] + $house['oldwamoumt']) * $house['nowcost'] + ($show['amoumt'] * $show['cost']);
    $amount = $house['amoumt'] + $house['oldamoumt'] + $house['wamoumt'] + $house['oldwamoumt'] + $show['amoumt'];
    // 更新house的数据
    if ($show['new']) {
      $updateHouse = [
        'nowcost' => round($total/$amount, 2),
        'amoumt' => $house['amoumt'] + $show['amoumt']
      ];
    } else {
      $updateHouse = [
        'nowcost' => round($total/$amount, 2),
        'oldamoumt' => $house['oldamoumt'] + $show['amoumt']
      ];
    }
    self::getModel()->startTrans();
    try {
      if ($updateHouse) {
        $res = HouseService::getModel()
          ->where('id', '=', $house['id'])
          ->update($updateHouse);
        if (!$res) {
          throw new \Exception('更新house失败');
        }
      }
      $res1 = self::getModel()
        ->where('id', '=', $id)
        ->delete();
      if (!$res1) {
        throw new \Exception('删除show失败');
      }
      self::getModel()->commit();
      return ['status' => true, 'msg' => 'ok'];
    } catch (\Exception $e) {
      self::getModel()->rollback();
      return ['status' => false, 'msg' => $e->getMessage()];
    }
  }

  /*
   * 返仓
   */
  public static function showReturn($id) {
    // 获取在展数据
    $show = ShowService::getModel()->find($id)->toArray();
    // 获取house数据
    $house = HouseService::getModel()
      ->where('productn', '=', $show['productn'])
      ->where('model', '=', $show['model'])
      ->find()
      ->toArray();
    $houseAmount = $house['amoumt'] + $house['oldamoumt'] + $house['wamoumt'] + $house['oldwamoumt'];
    // house数据修改
    $updateHouse = [];
    // 在展状态下返仓 -》 仓库旧品数量增加
    if ($show['states'] == 1) {
      $updateHouse = [
        'oldamoumt' => $house['oldamoumt'] + $show['amoumt'],
        'nowcost' => round(($house['nowcost'] * $houseAmount + $show['amoumt'] * $show['cost']) / ($houseAmount + $show['amoumt']), 2)
      ];
    // 待定状态下返仓 -》 仓库待售减少 仓库可售数量增加
    } else if ($show['states'] == 3) {
      // 是否全新
      if ($show['new']) {
        if ($house['wamoumt'] < $show['amoumt']) {
          return ['status' => false, 'msg' => '待发货库存不足'];
        }
        $updateHouse = [
          'wamoumt' => $house['wamoumt'] - $show['amoumt'],
          'amoumt' => $house['amoumt'] + $show['amoumt'],
          'nowcost' => round(($house['nowcost'] * $houseAmount + $show['amoumt'] * $show['cost']) / ($houseAmount + $show['amoumt']), 2)
        ];
      } else {
        if ($house['oldwamoumt'] < $show['amoumt']) {
          return ['status' => false, 'msg' => '待发货库存不足'];
        }
        $updateHouse = [
          'oldwamoumt' => $house['oldwamoumt'] - $show['amoumt'],
          'oldamoumt' => $house['oldamoumt'] + $show['amoumt'],
          'nowcost' => round(($house['nowcost'] * $houseAmount + $show['amoumt'] * $show['cost']) / ($houseAmount + $show['amoumt']), 2)
        ];
      }
    }

    self::getModel()->startTrans();
    try {
      // 修改show_t
      $res = self::getModel()
        ->where('id', '=', $id)
        ->update([
          'states' => 0,
          'backtime' => date('Y-m-d H:i:s')
        ]);
      if (!$res) {
        throw new \Exception('删除show失败');
      }
      // 修改house
      $res1 = HouseService::getModel()
        ->where('id', '=', $house['id'])
        ->update($updateHouse);
      if (!$res1) {
        throw new \Exception('更新house失败');
      }
      self::getModel()->commit();
      return ['status' => true, 'msg' => 'ok'];
    } catch (\Exception $e) {
      self::getModel()->rollback();
      return ['status' => false, 'msg' => $e->getMessage()];
    }

  }

  /*
   * 修改
   */
  public static function updateShow($id, $data) {
    // 修改展厅订单数据
    $showForm = $data['showForm'];
    // 修改详细数据
    $updateForm = $data['updateForm'];
    // 查看原数据
    $show = ShowService::getModel()->find($id)->toArray();
    // 获取仓库数据
    $house = HouseService::getModel()
      ->where('productn', '=', $show['productn'])
      ->where('model', '=', $show['model'])
      ->find()
      ->toArray();
    // 修改show_t中id数据
    $update = [
      'state' => $updateForm['state'] ? $updateForm['state'] : 0,
      'states' => $updateForm['states'] ? $updateForm['states'] : 1,
      'other' => $updateForm['other'] ? $updateForm['other'] : '',
      'date' => $showForm['date'] ? $showForm['date'] : null,
      'customer' => $showForm['customer'] ? $showForm['customer'] : '',
      'address' => $showForm['address'] ? $showForm['address'] : '',
      'cname' => $showForm['cname'] ? $showForm['cname'] : '',
      'phone' => $showForm['phone'] ? str_replace(' ', '',$showForm['phone']) : '',
      'installtime' => $showForm['installtime'] ? $showForm['installtime'] : null,
      'itime' => $showForm['itime'] ? $showForm['itime'] : null
    ];
    // 修改show_t中date-oid-customer数据
    $updateShow = [
      'date' => $showForm['date'] ? $showForm['date'] : null,
      'customer' => $showForm['customer'] ? $showForm['customer'] : '',
      'address' => $showForm['address'] ? $showForm['address'] : '',
      'cname' => $showForm['cname'] ? $showForm['cname'] : '',
      'phone' => $showForm['phone'] ? str_replace(' ', '',$showForm['phone']) : '',
      'installtime' => $showForm['installtime'] ? $showForm['installtime'] : null,
      'itime' => $showForm['itime'] ? $showForm['itime'] : null
    ];
    $shows = self::getModel()
      ->where('oid', '=', $show['oid'])
      ->where('date', '=', $show['date'])
      ->where('customer', '=', $show['customer'])
      ->select()
      ->toArray();
    $showIds = [];
    foreach ($shows as $showId){
      if ($showId['id'] != $id) {
        $showIds[] = $showId['id'];
      }
    }
    // 修改house数据
    $updateHouse = [];
    // 待定->在展(house待售减少)
    if ($show['states'] == 3 && $updateForm['states'] == 1) {
      if ($show['new']) {
        if ($house['wamoumt'] < $show['amoumt']) {
          return ['status' => false, 'msg' => '待售数量不足'];
        }
        $updateHouse['wamoumt'] = $house['wamoumt'] - $show['amoumt'];
      } else {
        if ($house['oldwamoumt'] < $show['amoumt']) {
          return ['status' => false, 'msg' => '待售数量不足'];
        }
        $updateHouse['oldwamoumt'] = $house['oldwamoumt'] - $show['amoumt'];
      }
    }
    self::getModel()->startTrans();
    try {
      // 修改ID对应数据
      self::getModel()->where('id', $id)->update($update);
      // 修改date-oid-customer对于数据
      if ($updateShow && $showIds) {
        foreach ($showIds as $v) {
          self::getModel()->where('id', $v)->update($updateShow);
        }
      }
      // 修改house
      if ($updateHouse) {
        $res1 = HouseService::getModel()
          ->where('id', $house['id'])
          ->update($updateHouse);
        if (!$res1) {
          throw new \Exception('修改house失败');
        }
      }
      self::getModel()->commit();
      return ['status' => true, 'msg' => 'ok'];
    } catch (\Exception $e) {
      self::getModel()->rollback();
      return ['status' => false, 'msg' => $e->getMessage()];
    }
  }

}